package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.result.Result;
import com.sky.service.IOrdersService;
import com.sky.service.IUserService;
import com.sky.service.IWorkspaceService;
import com.sky.vo.BusinessDataVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class WorkspaceServiceImpl implements IWorkspaceService {
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IOrdersService iOrdersService;

    @Override
    public BusinessDataVO getBusinessData(LocalDateTime beginDate,LocalDateTime endDate ) {
        //营业额
        LambdaQueryWrapper<Orders> lqw =new LambdaQueryWrapper<>();
        lqw.between(Orders::getOrderTime,beginDate,endDate);
        //新增用户数
        LambdaQueryWrapper<User> qw2 =new LambdaQueryWrapper<>();
        qw2.between(User::getCreateTime,beginDate,endDate);
        long newUser = iUserService.count(qw2);

        //总单数，指定天中
        long count = iOrdersService.count(lqw);
        if (count==0){
            //返回BusinessDataVo
            BusinessDataVO vo =BusinessDataVO
                    .builder()
                    .turnover(0.0)
                    .validOrderCount(0)
                    .orderCompletionRate(0.0)
                    .newUsers((int) newUser)
                    .unitPrice(0.0)
                    .build();
            return vo;
        }
        lqw.eq(Orders::getStatus,Orders.COMPLETED);
        //完成的订单数
        List<Orders> orderList = iOrdersService.list(lqw);
        if (orderList.isEmpty()){
            BusinessDataVO vo =BusinessDataVO
                    .builder()
                    .turnover(0.0)
                    .validOrderCount(0)
                    .orderCompletionRate(0.0)
                    .newUsers((int) newUser)
                    .unitPrice(0.0)
                    .build();
            return vo;
        }
        Double turnover = orderList.stream().map(s -> Double.parseDouble(s.getAmount() + "")).reduce(Double::sum).get();
        //有效订单数
        int validOrderCount = orderList.size();
        //订单完成率

        Double orderCompletionRate  =  (double) validOrderCount / count;
        //平均客单价
        long userCount = iUserService.count();

        Double unitPrice=turnover/userCount;

        //返回BusinessDataVo
        BusinessDataVO vo =BusinessDataVO
                .builder()
                .turnover(turnover)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .newUsers((int) newUser)
                .unitPrice(unitPrice)
                .build();
        return vo;
    }
}
